package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func main() {
	http.HandleFunc("/echo", func(writer http.ResponseWriter, request *http.Request) {
		connection, err := upgrader.Upgrade(writer, request, nil)
		if err != nil {
			fmt.Fprint(writer, "升级websocket失败")
			return
		}
		for {
			//读取数据
			messageType, msg, err := connection.ReadMessage()
			if err != nil {
				fmt.Fprint(writer, "读取websocket消息失败")
				return
			}
			fmt.Printf("%s sent: %s\n", connection.RemoteAddr(), string(msg))
			//写回数据
			if err := connection.WriteMessage(messageType, msg); err != nil {
				return
			}
		}
	})

	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		http.ServeFile(writer, request, "websockets.html")
	})
	http.ListenAndServe(":8989", nil)
}
